<template>
	<view class="busines-mod-list-top">
		<scroll-view id="tab-bar" class="scroll-h" :scroll-x="true" :show-scrollbar="false"
			:scroll-into-view="scrollId">
			<view v-for="(tab,index) in computedListData" :key="index" class="uni-tab-item" :id="index"
				:data-current="tab" @click="clickLeftItem(index)">
				<text class="uni-tab-item-title"
					:class="tabIndex== index ? 'uni-tab-item-title-active' : ''">{{tab.nf}}年</text>
			</view>
		</scroll-view>
	</view>
	<view class="busines-mod-list">
		<scroll-view scroll-y="true" :scroll-into-view="scrollId" scroll-with-animation @scroll="scrollEvt"
			refresher-enabled="true" :refresher-triggered="reload" @refresherrefresh="refresherrefresh"
			show-scrollbar="false" @scrolltolower="scrolltolower">
			<view class="list-item" v-for="(item,index) in computedListData" :key="item.nf" :id="'item'+index">
				<view v-for="itm in item.children" :key="itm.id">
					<uni-card :is-shadow="false" padding="0" spacing="0" margin="6" :key="index">
						<view class="busines-mod-list-title">
							<text>{{itm.zwyf+''}}</text>
						</view>
						<uni-list :border="false">
							<uni-list-item title="合计电量" :rightText="itm.dl + ''" />
							<uni-list-item title="应收电费" :rightText="moneyUtils(itm.ysdf) + ''" />
							<uni-list-item title="欠费金额" :rightText="moneyUtils(itm.ykdf) + ''" />
							<uni-list-item title="未开票金额" :rightText="moneyUtils(itm.wkdf) + ''" />
						</uni-list>
						<uni-tag @click="handleOpenInvoice(itm)" class="f-r" text="开 票" type="primary"
							style="margin: 5px; padding: 5px 10px;" />
						<uni-tag v-if="itm.pdfurl" type="error" style="margin: 5px; padding: 5px 10px;" @click="handleViewInvoice(itm)">查看</uni-tag>
					</uni-card>
				</view>
			</view>
			<uni-load-more :status="status" :icon-size="16" :content-text="contentText" />
		</scroll-view>
	</view>

</template>

<script setup lang="ts">
	import { getDzfpByYhbh } from "@/api/request/getDzfpByYhbh";
	import { moneyUtils } from "@/utils/index";
	import {invoiceOpen} from '@/api/request/invoice';
	import { onBeforeMount, watch, ref, computed } from 'vue';
	const props = defineProps({
		yhbh: {
			type: String,
			default: ""
		}
	})
	let tabIndex = ref(0)
	let scrollId = ref("")
	let distanceList = ref([])
	let timer = ref(null)
	let isLeftClick = ref(false)
	let listData = ref([]);
	let pagination = ref({ pageNum: 1, pageSize: 5 });
	let total = ref(0)
	let status = ref('noMore')
	let contentText = ref({
		contentdown: '上拉加载更多',
		contentrefresh: '加载中',
		contentnomore: '没有更多'
	})
	const reload = ref(false);
	onBeforeMount(() => {
		getListData()
	})
	watch(() => props.yhbh, () => {
		getListData()
	})
	const computedListData = computed(() => {
		let list = listData.value || []
		return list.reduce((result, item) => {
			let index = result.findIndex((it) => it.nf == item.nf);
			if (index == -1) {
				result.push({
					nf: item.nf,
					children: [item]
				});
			} else {
				result[index].children.push(item);
			}
			return result;
		}, []);
	})
	// 上拉加载
	function scrolltolower() {
		if (total.value <= listData.value.length) {
			status.value = 'noMore'
		} else {
			pagination.value.pageNum++
			status.value = 'loading'
			getListData()
		}
	}
	// 下拉刷新
	function refresherrefresh() {
		pagination.value.pageNum = 1
		reload.value = true
		getListData()
	}
	function getListData() {
		if (props.yhbh) {
			getDzfpByYhbh({
				data: {
					param: { yhbh: props.yhbh, },
					pagination: pagination.value
				},
				success: (res) => {
					let list = res.data
					listData.value = reload.value ? list : listData.value.concat(list);
					total.value = res.total
					status.value = res.total <= listData.value.length ? 'noMore' : 'more'
					reload.value = false
					uni.stopPullDownRefresh();
				},
				fail: (code, message) => {
					reload.value = false
					console.log(code, message)
				}
			})
		}
	}

	setTimeout(() => {
		getDistanceToTop();
	}, 500)

	function clickLeftItem(index : number) {
		isLeftClick.value = true
		tabIndex.value = index
		scrollId.value = 'item' + index
	}
	function getDistanceToTop() { //获取右侧各部分距离顶部的距离
		let selectorQuery = uni.createSelectorQuery()
		selectorQuery.selectAll('.list-item').boundingClientRect(function (rects) {
			rects.forEach(function (rect) {
				distanceList.value.push(rect.top)
			})
		}).exec()
	}

	// 元素滚动到顶部时，对应的 导航栏变为选中状态
	function scrollEvt(e) {
		// 点击导航栏引起的滚动不做判断
		if (isLeftClick.value) {
			isLeftClick.value = false
			return
		}
		// 防抖
		if (timer.value) {
			clearTimeout(timer.value)
		}
		timer.value = setTimeout(() => {
			let scrollTop = e.detail.scrollTop //滚动的高度
			// 找到位于顶部元素的索引，距离大于滚动高度的第一个元素的上一个元素就是此时位于顶部的元素
			let index = distanceList.value.findIndex(it => {
				// 滚动条的位置大于元素距离顶部位置的距离时，说明元素已经滑过了顶部
				return (it > scrollTop)
			}) - 1
			if (index == tabIndex.value) return
			tabIndex.value = index
		}, 200)
	}
	function handleViewInvoice(row){
		uni.showToast({
			title: '功能开发中',
			duration: 2000
		});
	}
	// 开票
	function handleOpenInvoice(row) {
		uni.showToast({
			title: '功能开发中',
			duration: 2000
		});
		// if (row.wkdf != '0' && !row.ysdf) {
		// 	uni.showToast({
		// 		title: '纳税信息未维护，无法开票，请先到营业厅维护纳税信息。',
		// 		duration: 2000
		// 	});
		// } else if (row.wkdf > 0) {
		// 	let contentHtml = `账务月份：${row.zwyf}\n 电费：${row.ysdf}\n开票金额：${row.wkdf}\n`;
		// 	uni.showModal({
		// 		title: "确认开票!",
		// 		content: contentHtml,
		// 		showCancel: false,
		// 		success: () => {
		// 			uni.showLoading({
		// 				title: '正在开票...',
		// 				mask: true
		// 			});
		// 			uni.request({
		// 			    url: 'http://wt.bspsd.cn/api/invoice/invoiceOpen',
		// 			    data: {
		// 			        yhbh: row.yhbh,
		// 			        zwyf: row.zwyf
		// 			    },
		// 			    header: {
		// 			        'zcyy':  1,
		// 					'platform': 'wechat'
		// 			    },
		// 				method: 'POST',
		// 			    success: (res) => {
		// 					uni.hideLoading();
		// 					let resp = JSON.parse(res.content);
		// 					if(resp.code == "9999") {
		// 					  // this.fetchData(); // 刷新列表
		// 					} else {
		// 						uni.showToast({
		// 							title: `${resp.message}(错误码：${resp.code})`,
		// 							duration: 2000
		// 						});
		// 					}
		// 			    },
		// 				fail: (e) => {
		// 					console.log(e)
		// 					uni.hideLoading();
		// 					uni.showToast({
		// 						title: "开票失败:" + e.errMsg,
		// 						duration: 2000
		// 					});
		// 				}
		// 			});
		// 		},
		// 	})
		// } else {
		// 	uni.showToast({
		// 		title: '未开票金额为0， 无法开具电子发票',
		// 		duration: 2000
		// 	});
		// }
	}
</script>
<style lang="scss" scoped>
</style>